package com.ruoyi.collect.engine.parser;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.collect.engine.client.MacCmsResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * JSON format resource parser
 * Parse JSON format MacCMS API response
 *
 * @author ruoyi
 * @date 2025-11-07
 */
@Component
public class JsonResourceParser implements IResourceParser {

    private static final Logger log = LoggerFactory.getLogger(JsonResourceParser.class);

    @Override
    public boolean support(String content) {
        if (content == null || content.isEmpty()) {
            log.debug("JSON parser: content is null or empty");
            return false;
        }

        String trimmedContent = content.trim();
        boolean isJson = (trimmedContent.startsWith("{") && trimmedContent.endsWith("}"))
                || (trimmedContent.startsWith("[") && trimmedContent.endsWith("]"));

        log.debug("JSON parser support check: starts with '{{': {}, ends with '}}': {}, result: {}",
            trimmedContent.startsWith("{"), trimmedContent.endsWith("}"), isJson);

        if (!isJson && trimmedContent.length() > 0) {
            log.debug("JSON parser: first char: '{}', last char: '{}'",
                trimmedContent.charAt(0), trimmedContent.charAt(trimmedContent.length() - 1));
        }

        return isJson;
    }

    @Override
    public MacCmsResponse parse(String content) {
        try {
            log.debug("Starting to parse JSON content, length: {}", content.length());

            // Use FastJSON2 to parse
            MacCmsResponse response = JSON.parseObject(content, MacCmsResponse.class);

            if (response == null) {
                throw new RuntimeException("JSON parse result is null");
            }

            // Handle flat format (guangsu/wujin APIs where page,pagecount,total,limit are at root level)
            // Convert flat format to nested PageInfo format for compatibility
            if (response.getPage() == null && response.getPageStr() != null) {
                MacCmsResponse.PageInfo pageInfo = new MacCmsResponse.PageInfo();
                try {
                    pageInfo.setPage(Integer.parseInt(response.getPageStr()));
                } catch (NumberFormatException e) {
                    pageInfo.setPage(1);
                }
                pageInfo.setPagecount(response.getPagecount());
                pageInfo.setRecordcount(response.getTotal());
                response.setPage(pageInfo);
                log.debug("Converted flat page format to nested PageInfo: page={}, pagecount={}, total={}",
                    pageInfo.getPage(), pageInfo.getPagecount(), pageInfo.getRecordcount());
            }

            // Log parse result
            if (response.getList() != null) {
                log.info("Successfully parsed JSON content, got {} vod items", response.getList().size());
            }

            return response;

        } catch (Exception e) {
            log.error("JSON parse failed: {}", e.getMessage());
            log.debug("JSON content first 500 chars: {}", content.length() > 500 ? content.substring(0, 500) : content);
            throw new RuntimeException("JSON parse failed: " + e.getMessage(), e);
        }
    }

    @Override
    public String getType() {
        return "JSON";
    }
}